// 默认切换间隔为10秒
const DEFAULT_INTERVAL = 10000;

// 初始化存储
chrome.runtime.onInstalled.addListener(() => {
  chrome.storage.sync.set({ interval: DEFAULT_INTERVAL });
});

// 主切换逻辑
let switchInterval;

function startSwitching(interval) {
  switchInterval = setInterval(async () => {
    const tabs = await chrome.tabs.query({ currentWindow: true });
    const activeTab = tabs.find(tab => tab.active);
    const nextIndex = (tabs.indexOf(activeTab)) + 1;
    const nextTab = tabs[nextIndex % tabs.length];
    
    if (nextTab) {
      chrome.tabs.update(nextTab.id, { active: true });
    }
  }, interval);
}

// 监听存储变化
chrome.storage.onChanged.addListener((changes) => {
  if (changes.interval) {
    clearInterval(switchInterval);
    if (changes.interval.newValue > 0) {
      startSwitching(changes.interval.newValue);
    }
  }
});

// 监听停止请求
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  if (request.action === 'stop') {
    clearInterval(switchInterval);
    chrome.storage.sync.set({ interval: 0 }, () => {
      sendResponse({ success: true });
    });
    return true; // 保持消息端口打开以等待异步响应
  }
});

// 初始化启动
chrome.storage.sync.get('interval', (data) => {
  const interval = data.interval || DEFAULT_INTERVAL;
  if (interval > 0) {
    startSwitching(interval);
  }
});
